<?php

namespace app\admin\services;

use app\admin\controller\NewOrder;
use app\admin\model\LogModel;
use app\admin\model\OrderInModel;
use app\admin\model\ShopModel;
use think\facade\Db;

class CmdService extends BaseService
{
    public static function resetArea(){
        $params=[
            'where'=>[
                ['id','>',1474650],
                ['id','<',1476742],
            ],
            'field'=>'id,shop_id',
            'page'=>'all'
        ];
        $list=OrderInModel::getList($params)->toArray();
        $shopList=ShopModel::column('area','shop_id');
        foreach ($list as $item){
            OrderInModel::where('id',$item['id'])->update([
//                'id'=>$item['id'],
                'area'=>$shopList[$item['shop_id']]
            ]);
        }
    }

    /**
     * 从百度拉取订单
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getOrderList(){
        $url='https://api.baidu.com/json/sms/service/PlatOrderBusinessQueryService/getPartConsignOrderList';
        $shopList=ShopModel::getList([
            'where'=>[
//                ['shop_id','in','35034293']
            ],
            'page'=>'all'
        ])->toArray();
        $startTime=date('Y-m-d',strtotime('-1 day'));
        $endTime=date('Y-m-d',strtotime('+1 day'));
//        $startTime='2023-02-01';
//        $endTime='2023-03-01';
        foreach ($shopList as $shop) {
            $page=0;
            $pageSize=50;
            $total=51;
            if(!empty($shop['accesstoken']['accessToken']))
                $header=[
                    'authorityType' => 5,
                    'userName' => $shop['username'],
                    'accessToken' => $shop['accesstoken']['accessToken'],
                ];
            else{
                $header=[
                    'authorityType' => 2,
                    'username' => $shop['username'],
                    'password' => $shop['password'],
                    'token' => $shop['token'],
                ];
            }
            while (($page*$pageSize)<=$total) {
                $postData = [
                    'header' => $header,
                    'body' => [
                        'startUpdateTime' => $startTime,
                        'endUpdateTime' => $endTime,
                        'appId' => 5,
                        'pageNum' => $page+1,
                        'pageSize' => $pageSize,
//                        'orderId'=>'90420745082014'
                    ]
                ];
                $res = json_decode(post($url, json_encode($postData)), true);
                if (!empty($res['body']['data'][0]['list'])) {
                    foreach ($res['body']['data'][0]['list'] as $item) {
                        if (!$order=OrderInModel::where([['order_id', '=', $item['orderId']]])->find())
                        {
                            $orderInfo=NewOrderService::handleOrderSatus($item,$shop);
                            OrderInModel::insert($orderInfo);
                            echo 'insert-'.$item['orderId'] . "-$page-$total\n";
                        }else{
                            $orderInfo=NewOrderService::handleOrderSatus($item,$shop);
                            $order->save($orderInfo);
                            echo 'save-'.$item['orderId'] . "-$page-$total\n";
                        }
                    }
                }
                $page++;
                $total=($res['body']['data'][0]['total'])??$total;
                echo $page.'-'.$pageSize.'-'.$total."\n";
            }
        }
    }

    /**
     * 从百度拉取售后单
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getRefundList(){
        $url='https://api.baidu.com/json/sms/service/PlatBusinessOrderRefundService/queryOrderRefundList';
        $shopList=ShopModel::getList([
            'where'=>[
//                ['shop_id','=','1895515']
            ],
            'page'=>'all'
        ])->toArray();
        $startTime=date('Y-m-d',strtotime('-1 day'));
        $endTime=date('Y-m-d',strtotime('+1 day'));
        foreach ($shopList as $shop) {
            $page=1;
            $pageSize=50;
            $total=51;
            if(!empty($shop['accesstoken']['accessToken']))
                $header=[
                    'authorityType' => 5,
                    'userName' => $shop['username'],
                    'accessToken' => $shop['accesstoken']['accessToken'],
                ];
            else{
                $header=[
                    'authorityType' => 2,
                    'username' => $shop['username'],
                    'password' => $shop['password'],
                    'token' => $shop['token'],
                ];
            }
            while ($page*$pageSize<=($total)) {
                $postData = [
                    'header' => $header,
                    'body' => [
                        'startCreateTime' => $startTime,
                        'endCreateTime' => $endTime,
//                        'startCreateTime' => '2022-12-1',
//                        'endCreateTime' => '2022-12-10',
                        'appId' => 5,
                        'pageNum' => $page,
                        'pageSize' => $pageSize,
                    ]
                ];
                $res = json_decode(post($url, json_encode($postData)), true);
                if (!empty($res['body']['data'][0]['list'])) {
                    foreach ($res['body']['data'][0]['list'] as $item) {
                        if ($order=OrderInModel::where([['order_id', '=', $item['orderId']]])->find())
                        {
                            $orderInfo=[
                                'order_id'=>$item['orderId'],
                                'order_refund_info'=>$item
                            ];
                            $order->save($orderInfo);
                            echo 'save-'.$item['orderId'] . "\n";
                        }
                    }
                }
                $page++;
                $total=($res['body']['data'][0]['total'])??$total;
            }
        }
    }

    /**
     * 删除重复订单
     * @return void
     */
    public static function deleteDuplicateOrders(){
        $date=date('Y-m-d',strtotime('-1 day'));
        $sql="DELETE FROM order_in WHERE  create_time like '$date%' and  id NOT IN (
                SELECT t.min_id FROM (
                    -- 过滤出重复多余的数据，比如，如果所有记录中存在1条记录是user_name=zhangsan的，那么就取出它；
                    -- 如果所有记录中存在多条记录是user_name=lisi的，那么只取其中1条，其他的不查询出来
                    SELECT MIN(id) AS min_id FROM order_in where create_time like '$date%' GROUP BY order_id
              ) t
            )";
        Db::query($sql);
    }

    /**
     * 批量刷新token任务
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function refreshToken(){
        $params=[
            'where'=>[
            ],
            'page'=>'all',
            'with'=>[
                'mainbody'=>function($query){
                    $query->withField(['id','appid','secretkey']);
                }
            ]
        ];
        $shopList=ShopModel::getList($params);
        foreach ($shopList as $item)
        {
            if($item->accesstoken) {
                echo $item->shop_id . '-';
                if (NewOrderService::refreshAccessToken($item->mainbody->appid, $item->accesstoken['refreshToken'], $item->mainbody->secretkey, $item->accesstoken['userId'], $item))
                    echo 'true';
                else {
                    echo 'false';
                }
                echo "\n";
            }
        }
    }

    /**
     * 更新done=0的订单
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function deleteDoneFalse(){
        $list=LogModel::where([
            ['done','in',[0,1,2]],
            ['create_time','<=',date('Y-m-d H:i:s',strtotime('-1 hour'))],
            ['create_time','>=','2023-02-15 11:40:00']
        ])->limit(1000)
//            ->order('id desc')
            ->field('id,order_id,req_data,done')->select();
        foreach ($list as $item){
            echo $item->order_id.'-';
            $p=json_decode($item->req_data,true);
            $p['log_id']=$item->id;
            echo 'post'.json_encode(NewOrderService::handle($p));
            $item->done = 5;
            $item->save();
            echo "\n";
        }
    }

    /**
     * 更新售后任务
     * @return void
     */
    public static function updateRefund(){
        $orderList=OrderInModel::getList([
            'where'=>[
                ['order_refund_info','not like','%complaintFlowList%'],
                ['order_refund_info','not in',['[]','{}']]
//                ['id','=',90752773793275],
            ],
            'page'=>'all'
        ]);
        $shopList=ShopModel::column('*','shop_id');
        $header=[
            'Content-Type: application/json'
        ];
        foreach ($orderList as $item) {
            $params = [
                'header' => [
                    'userName' => $shopList[$item->shop_id]['username'],
                    'accessToken' => $shopList[$item->shop_id]['accesstoken']['accessToken'],
                ],
                'body' => [
                    'refundId' => $item->order_refund_info['refundId'],
                    'ucid' => $item->ucid,
                    'shopId' => $item->shop_id,
                    'appId' => 5
                ]
            ];
            $url = 'https://api.baidu.com/json/sms/service/PlatBusinessOrderRefundService/queryOrderRefundInfo';
            $res = json_decode(post($url, json_encode($params), $header), true);
            print_r($res);
            if(!empty($res['body']['data'][0])){
                $item->order_refund_info=$res['body']['data'][0];
                $item->save();
            }
        }
    }

    /**
     * 检测token过期通知robot
     * @return void
     */
    public static function pushMsgToRobot(){
        $params=[
            'where'=>[
//                ['id','in',[164,165]]
            ['area','=','hb'],
            ['mainbody_id','<>',0]
            ],
            'page'=>'all',
        ];
        $shopList=ShopModel::getList($params);
        $shopNameList=[];
        foreach ($shopList as $item)
        {
            if($item->accesstoken)
            {
                if (strtotime($item->accesstoken['expiresTime'])<time())
                {
                    $shopNameList[] = $item->username;
                }
            }else{
                $shopNameList[] = $item->username;
            }
        }
        if($shopNameList) {
            $url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=9cb812f7-8b11-41bd-a1e1-e09cb898d2f9';
            $data = [
                'msgtype' => 'markdown',
                'markdown' => [
                    'content' => "以下店铺token自动更新失败，请及时授权更新\n" . ">" . implode("\n", $shopNameList)
                ]
            ];
            post($url, json_encode($data));
        }
    }
}
